Caesar Alg

Brightcells 7 年之前
父節點
當前提交
f38d3bf980
共有 2 個文件被更改,包括 32 次插入5 次删除
  1. 10 5
      api/encrypt_views.py
  2. 22 0
      utils/algorithm/caesar.py

+ 10 - 5
api/encrypt_views.py

@@ -2,7 +2,6 @@
2 2
 
3 3
 from __future__ import division
4 4
 
5
-import json
6 5
 import random
7 6
 
8 7
 from django_response import response
@@ -10,13 +9,15 @@ from logit import logit
10 9
 
11 10
 from mch.models import BrandInfo, ModelImageInfo, ModelInfo
12 11
 from utils.algorithm.b64 import b64_decrypt, b64_encrypt
12
+from utils.algorithm.caesar import caesar_decrypt, caesar_encrypt
13 13
 from utils.algorithm.rsalg import rsa_decrypt, rsa_encrypt
14 14
 
15 15
 
16
-# CIPHER_ALGORITHM = ('B64', 'RSA')
17
-CIPHER_ALGORITHM = ('B64', )
16
+# CIPHER_ALGORITHM = ('CAESAR', 'B64', 'RSA')
17
+CIPHER_ALGORITHM = ('CAESAR', 'B64')
18 18
 
19 19
 CIPHER_PREFIX = {
20
+    'CAESAR': '0',
20 21
     'B64': '1',
21 22
     'RSA': '2',
22 23
 }
@@ -28,7 +29,9 @@ def encrypt(request):
28 29
 
29 30
     alg = random.choice(CIPHER_ALGORITHM)
30 31
 
31
-    if alg == 'B64':
32
+    if alg == 'CAESAR':
33
+        ciphertext = caesar_encrypt(plaintext)
34
+    elif alg == 'B64':
32 35
         ciphertext = b64_encrypt(plaintext)
33 36
     elif alg == 'RSA':
34 37
         ciphertext = rsa_encrypt(plaintext)
@@ -46,7 +49,9 @@ def decrypt(request):
46 49
 
47 50
     alg, ciphertext = ciphertext.split('+', 1)
48 51
 
49
-    if alg == CIPHER_PREFIX['B64']:
52
+    if alg == CIPHER_PREFIX['CAESAR']:
53
+        plaintext = caesar_decrypt(ciphertext)
54
+    elif alg == CIPHER_PREFIX['B64']:
50 55
         plaintext = b64_decrypt(ciphertext)
51 56
     elif alg == CIPHER_PREFIX['RSA']:
52 57
         plaintext = rsa_decrypt(ciphertext)

+ 22 - 0
utils/algorithm/caesar.py

@@ -0,0 +1,22 @@
1
+# -*- coding: utf-8 -*-
2
+
3
+import random
4
+import string
5
+
6
+
7
+fromstr = '0123456789#'
8
+tostr = 'RKxyjwzcs6U'
9
+
10
+
11
+def generate_tostr(n):
12
+    fromstrlist = list(string.letters + string.digits)
13
+    random.shuffle(fromstrlist)
14
+    return ''.join(fromstrlist)[:n]
15
+
16
+
17
+def caesar_encrypt(plaintext):
18
+    return str(plaintext).translate(string.maketrans(fromstr, tostr))
19
+
20
+
21
+def caesar_decrypt(ciphertext):
22
+    return str(ciphertext).translate(string.maketrans(tostr, fromstr))